/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import controladores.BancoJpaController;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.InputMap;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.plaf.basic.BasicListUI;
import javax.swing.table.DefaultTableModel;
import modelo.Banco;

/**
 *
 * @author Ususario
 */
public class GestionBanco extends javax.swing.JInternalFrame {

    List<String> bancos = new ArrayList<String>();
    private DefaultTableModel modelo1;
    String datos1[][] = {};
    String columnas1[] = {"Codigo", "Nombre"};
    boolean nuevo = false;
    BancoJpaController controlerBanco = new BancoJpaController();

    public GestionBanco() {
        modelo1 = new DefaultTableModel(datos1, columnas1);
        initComponents();
        List<Banco> bancos = controlerBanco.findBancoEntities();
        for (int i = 0; i < bancos.size(); i++) {
            Banco b = bancos.get(i);
            modelo1.addRow(new Object[]{});
            modelo1.setValueAt(b.getCodigo(), i, 0);
            modelo1.setValueAt(b.getNombre(), i, 1);
        }
        masterTable.setModel(modelo1);
        InputMap im = masterTable.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        im.put(KeyStroke.getKeyStroke("DOWN"), "none");
        im.put(KeyStroke.getKeyStroke("UP"), "none");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell

            }};
            codigoLabel = new javax.swing.JLabel();
            nombreLabel = new javax.swing.JLabel();
            codigoField = new javax.swing.JTextField();
            nombreField = new javax.swing.JTextField();
            saveButton = new javax.swing.JButton();
            refreshButton = new javax.swing.JButton();
            newButton = new javax.swing.JButton();
            deleteButton = new javax.swing.JButton();

            setTitle("Gestionar bancos");
            setPreferredSize(new java.awt.Dimension(885, 440));

            jPanel2.setPreferredSize(new java.awt.Dimension(800, 370));

            masterTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Codigo", "Nombre"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class
                };
                boolean[] canEdit = new boolean [] {
                    false, false
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            masterTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    masterTableMouseClicked(evt);
                }
            });
            masterScrollPane.setViewportView(masterTable);

            codigoLabel.setText("Codigo:");

            nombreLabel.setText("Nombre:");

            codigoField.setEnabled(false);

            nombreField.setEnabled(false);

            saveButton.setText("Guardar");
            saveButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveButtonActionPerformed(evt);
                }
            });

            refreshButton.setText("Refrescar");
            refreshButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    refreshButtonActionPerformed(evt);
                }
            });

            newButton.setText("Nuevo");
            newButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    newButtonActionPerformed(evt);
                }
            });

            deleteButton.setText("Borrar");
            deleteButton.setEnabled(false);
            deleteButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    deleteButtonActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addComponent(newButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(deleteButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(refreshButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(saveButton))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel2Layout.createSequentialGroup()
                                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(codigoLabel)
                                        .addComponent(nombreLabel))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(codigoField)
                                        .addComponent(nombreField)))
                                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(codigoLabel)
                        .addComponent(codigoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(nombreLabel)
                        .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton)
                        .addComponent(refreshButton)
                        .addComponent(deleteButton)
                        .addComponent(newButton))
                    .addContainerGap())
            );

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(35, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(30, Short.MAX_VALUE))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            if (codigoField.getText().trim().equals("") || nombreField.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(null, "Por favor llene todos los campos");
            } else {
                if (nuevo && controlerBanco.findBySingle("codigo", codigoField.getText().trim().toUpperCase()) != null) {
                    JOptionPane.showMessageDialog(null, "Ya existe un banco registrado con este codigo", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    if (!nuevo) {
                        Banco aux2 = controlerBanco.findBySingle("codigo", codigoField.getText().trim().toUpperCase());
                        List<Banco> bancos0 = controlerBanco.findBancoEntities();
                        Banco seleccionado = bancos0.get(masterTable.getSelectedRow());
                        if (aux2 != null && aux2.getIdbanco() != seleccionado.getIdbanco()) {
                            JOptionPane.showMessageDialog(null, "Ya existe un banco registrado con este codigo", "Error", JOptionPane.ERROR_MESSAGE);
                        } else {
                            seleccionado.setNombre(nombreField.getText().trim().toUpperCase());
                            seleccionado.setCodigo(codigoField.getText().trim().toUpperCase());
                            controlerBanco.edit(seleccionado);
                            List<Banco> bancos = controlerBanco.findBancoEntities();
                            modelo1 = new DefaultTableModel(datos1, columnas1);
                            for (int i = 0; i < bancos.size(); i++) {
                                Banco aux = bancos.get(i);
                                modelo1.addRow(new Object[]{});
                                modelo1.setValueAt(aux.getCodigo(), i, 0);
                                modelo1.setValueAt(aux.getNombre(), i, 1);
                            }
                            masterTable.setModel(modelo1);
                            codigoField.setText("");
                            codigoField.setEnabled(false);
                            nombreField.setText("");
                            nombreField.setEnabled(false);
                        }
                    } else {
                        Banco nuevoB = new Banco();
                        nuevoB.setCodigo(codigoField.getText().trim().toUpperCase());
                        nuevoB.setNombre(nombreField.getText().trim().toUpperCase());
                        controlerBanco.create(nuevoB);
                        modelo1.addRow(new Object[]{});
                        modelo1.setValueAt(nuevoB.getCodigo(), masterTable.getRowCount() - 1, 0);
                        modelo1.setValueAt(nuevoB.getNombre(), masterTable.getRowCount() - 1, 1);
                        masterTable.setModel(modelo1);
                        codigoField.setText("");
                        codigoField.setEnabled(false);
                        nombreField.setText("");
                        nombreField.setEnabled(false);


                    }
                }



            }

        } catch (Exception rex) {
            /*rex.printStackTrace();
             entityManager.getTransaction().begin();
             List<vista.Banco> merged = new ArrayList<vista.Banco>(list.size());
             for (vista.Banco b : list) {
             merged.add(entityManager.merge(b));
             }
             list.clear();
             list.addAll(merged);*/
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        masterTable.clearSelection();
        codigoField.setEnabled(false);
        codigoField.setText("");
        nombreField.setEnabled(false);
        nombreField.setText("");
        nuevo = false;
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        masterTable.clearSelection();
        codigoField.setEnabled(true);
        codigoField.setText("");
        nombreField.setEnabled(true);
        nombreField.setText("");
        nuevo = true;
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        /*List<vista.Banco> toRemove = new ArrayList<vista.Banco>(selected.length);
         for (int idx = 0; idx < selected.length; idx++) {
         vista.Banco b = list.get(masterTable.convertRowIndexToModel(selected[idx]));
         toRemove.add(b);
         entityManager.remove(b);
         }
         list.removeAll(toRemove);*/
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        String codigo = (String) modelo1.getValueAt(masterTable.getSelectedRow(), 0);
        Banco p = controlerBanco.findBySingle("codigo", codigo);
        codigoField.setText(p.getCodigo());
        codigoField.setEnabled(true);
        nombreField.setText(p.getNombre());
        nombreField.setEnabled(true);
        nuevo = false;


    }//GEN-LAST:event_masterTableMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField codigoField;
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JTextField nombreField;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}
